import { ThemeCssType } from "@/stores/edit-pages-store";
import { isEmpty } from "lodash-es";

export function findOrCreateStyle({
  classId,
  doc,
  before,
  id,
}: {
  classId: string;
  doc?: Document;
  before?: string;
  id?: string;
}) {
  doc = doc || document;
  let varStyleTag = doc.getElementById(classId);
  if (!varStyleTag) {
    varStyleTag = doc.createElement("style");
    varStyleTag.id = classId;
    varStyleTag.setAttribute("class", id || "");
    const beforeStyleTag = doc.getElementsByClassName(before || "")?.[0] as HTMLElement;
    // 如果存在before则插入到before之前，否则插入到body中
    if (beforeStyleTag) {
      beforeStyleTag.before(varStyleTag);
    } else {
      doc.body.appendChild(varStyleTag);
    }
  }

  return varStyleTag;
}

export function insertStyle({
  style,
  classId,
  id,
  doc,
  before,
}: {
  style: string;
  classId: string;
  id?: string;
  doc?: Document;
  before?: string;
}) {
  const varStyleTag = findOrCreateStyle({
    classId: "jedi-" + classId,
    doc,
    before,
    id,
  });
  varStyleTag.innerHTML = style;

  if (!style) {
    varStyleTag.remove();
  }
}

// export function addStyle(style: string, id: string) {
//   const varStyleTag = findOrCreateStyle({classId: id});
//   varStyleTag.innerHTML += style;
// }

// export async function getScssToCss(scss: string) {
//   const sassModule = await import("sass");
//   const { compileString } = sassModule;
//   const result = compileString(scss);
//   return result.css;
// }

export function toClassCSSStr(css: Record<string, any>, className: string) {
  let str = `.${className} {\n`;
  for (let key in css) {
    let value = css[key];
    if (!value) {
      continue;
    }
    str += `\t${key}: ${value};\n`;
  }
  str += "}";
  return str;
}

const customClassPrefix = "customClassStyle";
const cooptedClassPrefix = "cooptedClassStyle";
export function getCleanId(id: string) {
  return id.replace("u:", "");
}
export function getCustomClassName(id: string) {
  const fid = getCleanId(id);
  return `${customClassPrefix}-${fid}`;
}
export function getCooptedClassName(id: string) {
  const fid = getCleanId(id);
  return `${cooptedClassPrefix}-${fid}`;
}
export function setCustomClassStylesheet({
  style,
  id,
  doc = document,
  idPrefix = "",
}: {
  style: Record<string, any> | null | undefined;
  id: string;
  doc?: Document;
  idPrefix?: string;
}) {
  const fid = getCleanId(id); //u:fasfasf23 => fasfasf23
  const classId = getCustomClassName(id); //customClassStyle-fasfasf23
  const classStyle = isEmpty(style) ? "" : toClassCSSStr(style, classId);

  const element = document.querySelector(`[data-component-id="${id}"]`);
  if (classStyle) {
    element?.classList.add(classId);
  } else {
    element?.classList.remove(classId);
  }
  insertStyle({
    style: classStyle,
    classId,
    doc,
    id: fid,
  });
}
export function setThemeCssClassStylesheet({
  style,
  id,
  doc = document,
  idPrefix = "",
}: {
  style: ThemeCssType | null | undefined;
  id: string;
  doc?: Document;
  idPrefix?: string;
}) {
  const fid = getCleanId(id); //u:fasfasf23 => fasfasf23
  const classId = fid; // 无需加上前缀cooptedClassPrefix，
  const classStyle = isEmpty(style) ? "" : getThemeCssStyleStr(style, id);

  const element = document.querySelector(`[data-component-id="${id}"]`);
  const className = getCooptedClassName(id);
  if (classStyle) {
    element?.classList.add(className);
  } else {
    element?.classList.remove(className);
  }
  insertStyle({
    style: classStyle,
    classId,
    doc,
    id: fid,
    before: fid,
  });
}

function getThemeCssStyleStr(themeCss: ThemeCssType, id: string) {
  let obj = {};
  for (const key in themeCss) {
    if (key === "cooptedStyle") {
      const sObj = themeCss[key];
      for (const sKey in sObj) {
        if (sKey === "padding:default") {
          obj = { ...obj, ...{ padding: sObj[sKey] } };
        } else if (sKey === "margin:default") {
          obj = { ...obj, ...{ margin: sObj[sKey] } };
        } else if (sKey === "border-radius:default") {
          obj = { ...obj, ...{ "border-radius": sObj[sKey] } };
        }
      }
    }
  }
  return isEmpty(obj) ? "" : toClassCSSStr(obj, getCooptedClassName(id));
}
